package com.xrit.sunnyday.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.pojo.Permission;
import com.xrit.sunnyday.pojo.Role;
import com.xrit.sunnyday.pojo.User;
import com.xrit.sunnyday.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        User user = userService.findByUsername(username);
        if(null!=user) {
            //用户密码
            String password = user.getPassword();
            /**
             * 提供登陆用户信息  username password 权限集合 authorities
             * @param username
             * @return
             * @throws UsernameNotFoundException
             */
            List<GrantedAuthority> authority = new ArrayList<GrantedAuthority>();
            SimpleGrantedAuthority sai=null;
            //获取用户拥有的角色
            Set<Role> roles = user.getRoles();
            if(null!=roles){
                for (Role role : roles) {
                    sai = new SimpleGrantedAuthority(role.getKeyword());
                    authority.add(sai);
                    // 权限, 角色下的所有权限
                    Set<Permission> permissions=role.getPermissions();
                    if (null!=permissions){
                        for (Permission permission : permissions) {
                            sai = new SimpleGrantedAuthority(permission.getKeyword());
                            authority.add(sai);
                        }
                    }
                }

            }
            return new org.springframework.security.core.userdetails.User(username,password,authority);
        }
        return null;
    }
}
